package com.example.spsaveqqty;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.spsaveqqty.userManage.User;
import com.example.spsaveqqty.userManage.UserDao;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class EditUserInfoActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_edit_username;//用户名
    private TextView tv_edit_slogan;//个性签名
    private TextView tv_edit_sex;//性别
    private TextView tv_edit_birthday;//生日
    private TextView tv_edit_location;//地区
    private ImageView img_user;//头像
    private ContentValues values;
    private User user;
    private UserDao userdao;


    public static final int CHOOSE_PHOTO=1;//相册
    public static final int TAKE_PHOTO =2;//拍照
    private Uri imageUri;
    String index = "";		//	作为拍照还是相册的标识
    String info = "";		//	uri变成字符串

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user_info);
        //初始化页面：
        userdao =new UserDao(this);
        requestWritePermission();
        init();

    }

    private void init() {
        tv_edit_username = (TextView) findViewById(R.id.tv_edit_username);
        tv_edit_slogan = (TextView) findViewById(R.id.tv_edit_slogan);
        tv_edit_sex = (TextView) findViewById(R.id.tv_edit_sex);
        tv_edit_birthday = (TextView) findViewById(R.id.tv_edit_birthday);
        tv_edit_location = (TextView) findViewById(R.id.tv_edit_location);
        img_user = (ImageView) findViewById(R.id.img_user);

        tv_edit_slogan.setSelected(true);//用于设置跑马灯
        tv_edit_username.setSelected(true);//用于设置跑马灯

        user = userdao.findUserByUserName(User.USERNAME);

        //设置展示界面上对应的user信息
        //设置头像：
        if (!TextUtils.isEmpty(user.getFlag())){
            if (user.getFlag().equals("1")){		//	相册
                Bitmap bitmap = BitmapFactory.decodeFile(user.getPicture());
                bitmap = Bitmap.createScaledBitmap(bitmap,200,200,true);
                bitmap = toRoundBitmap(bitmap);//调用自己写的方法把bitmap转成圆形
                img_user.setImageBitmap(bitmap);
            }else if (user.getFlag().equals("2")){	//	拍照
                Uri imgUri = Uri.parse(user.getPicture());
                try {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgUri));
                    bitmap = Bitmap.createScaledBitmap(bitmap,200,200,true);
                    bitmap = toRoundBitmap(bitmap);//调用自己写的方法把bitmap转成圆形
                    img_user.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        tv_edit_username.setText(user.getUsername());
        tv_edit_slogan.setText(user.getSlogan());
        if (user.getSex() == 0) {//0代表没有值
            tv_edit_sex.setText("未填写");
        } else if (user.getSex() == 1) {//1代表男
            tv_edit_sex.setText("男");
        } else if (user.getSex() == 2) {//2代表女
            tv_edit_sex.setText("女");
        }
        tv_edit_birthday.setText(user.getBirthday());
        tv_edit_location.setText(user.getLocation());

        //设置点击事件：
        tv_edit_slogan.setOnClickListener(this);
        tv_edit_sex.setOnClickListener(this);
        tv_edit_birthday.setOnClickListener(this);
        tv_edit_location.setOnClickListener(this);

        //设置头像的点击事件:
        img_user.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_user://点击头像
                showPopueWindow();
                break;
            case R.id.tv_edit_slogan:
                AlertDialog.Builder builder = new AlertDialog.Builder(EditUserInfoActivity.this);
                LayoutInflater inflater = LayoutInflater.from(EditUserInfoActivity.this);
                View viewDialog = inflater.inflate(R.layout.edit_slogan_alter, null);
                final EditText slogan = (EditText) viewDialog.findViewById(R.id.et_alter_slogan);
                slogan.setText(user.getSlogan());
                builder.setView(viewDialog);
                builder.setTitle("编辑简介");

                builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (TextUtils.isEmpty(slogan.getText().toString().trim())) {
                            Toast toast = Toast.makeText(getApplicationContext(), "请输入个人简介", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER | Gravity.CENTER, 0, 0);
                            toast.show();
                        } else {//更新简介
                            values = new ContentValues();
                            values.put("slogan", slogan.getText().toString());
                            userdao.updateUserInfo(values,User.USERNAME);
                            //修改后刷新本页数据
                            Intent intent = new Intent(EditUserInfoActivity.this, EditUserInfoActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.create().show();
                break;
            case R.id.tv_edit_sex:
                AlertDialog.Builder builderForSex = new AlertDialog.Builder(EditUserInfoActivity.this);
                LayoutInflater inflaterForSex = LayoutInflater.from(EditUserInfoActivity.this);
                View viewDialogForSex = inflaterForSex.inflate(R.layout.edit_sex_alter, null);
                final RadioGroup sex = (RadioGroup) viewDialogForSex.findViewById(R.id.rg_alter_sex);
                // 设置单选按钮初始值
                if(user.getSex()==1){
                    sex.check(R.id.rb_alter_sex1);//设置 男 被选中
                }else if(user.getSex()==2){
                    sex.check(R.id.rb_alter_sex2);//设置 女 被选中
                }else{
                    sex.clearCheck();//清空选中
                }
                values = new ContentValues();
                //给单选按钮组设置选择监听
                sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        if(group.getCheckedRadioButtonId()==R.id.rb_alter_sex1){
                            values.put("sex", 1);
                        }else if (group.getCheckedRadioButtonId()==R.id.rb_alter_sex2){
                            values.put("sex", 2);
                        }
                    }
                });
                builderForSex.setView(viewDialogForSex);
                builderForSex.setTitle("编辑性别");
                builderForSex.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        userdao.updateUserInfo(values,User.USERNAME);
                        //修改后刷新本页数据
                        Intent intent = new Intent(EditUserInfoActivity.this, EditUserInfoActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
                builderForSex.setNegativeButton("取消", null);
                builderForSex.create().show();
                break;
            case R.id.tv_edit_birthday:
                AlertDialog.Builder builderForBirthday = new AlertDialog.Builder(EditUserInfoActivity.this);
                LayoutInflater inflaterForBirthday = LayoutInflater.from(EditUserInfoActivity.this);
                View viewDialogForBirthday = inflaterForBirthday.inflate(R.layout.edit_birthday_alter, null);
                final DatePicker birthday = (DatePicker) viewDialogForBirthday.findViewById(R.id.et_alter_birthday);
                //birthday.set(user.getSlogan()); 设置时间选择器初始值
                builderForBirthday.setView(viewDialogForBirthday);
                builderForBirthday.setTitle("编辑生日");

                builderForBirthday.setPositiveButton("保存", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        values = new ContentValues();
                        values.put("birthday", birthday.getYear() + "-" + (birthday.getMonth() + 1) + "-" + birthday.getDayOfMonth());
                        userdao.updateUserInfo(values,User.USERNAME);

                        //修改后刷新本页数据
                        Intent intent = new Intent(EditUserInfoActivity.this, EditUserInfoActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
                builderForBirthday.setNegativeButton("取消", null);
                builderForBirthday.create().show();
                break;
            case R.id.tv_edit_location:
                Intent intent = new Intent(EditUserInfoActivity.this, EditLocActivity.class);
                startActivity(intent);
                break;
        }
    }

    //使按返回键时直接返回个人中心：
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //点击home键
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        //点击返回键
        else if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(EditUserInfoActivity.this, PersonalCenterActivity.class);
            startActivity(intent);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        //  根据Uri找到这张照片的位置，将它解析成Bitmap对象，然后将把它设置到imageView中显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        bitmap = Bitmap.createScaledBitmap(bitmap,200,200,true);

                        bitmap = toRoundBitmap(bitmap);//调用自己写的方法把bitmap转成圆形
                        info = "" + imageUri;
                        index = "2";
                        updatepicture();//把图片存入数据库
                        img_user.setImageBitmap(bitmap);//把页面上的图片换掉
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                /**
                 *          之所以这样做是是因为，Android 系统从4.4版本开始，选取相册图片不再返回图片真实的Uri了，而是一个封装过的Uri，因此
                 *          如果是4.4版本以上的手机就需要对这个Uri进行解析才行
                 */
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {      //  如果是在4.4及以 上 系统的手机就调用该方法来处理图片
                        handleImageOnKitKat(data);
                    } else {
                        handleImageBeforeKitKat(data);      //  如果是在4.4以 下 系统的手机就调用该方法来处理图片
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     *          如何解析这个封装过的Uri
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this,uri)){
            //  如果返回的Uri是 document 类型的话，那就取出 document id 进行处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id = docId.split(":")[1];        //  解析出数字格式id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                imagePath = getImagePath(contentUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            //  如果是 content 类型的Uri，则使用普通方式处理
            imagePath = getImagePath(uri,null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            //  如果是 file 类型的 Uri ，直接获取图片路径即可
            imagePath = uri.getPath();
        }
        displayImage(imagePath);        //  拿到图片路径后，在调用 displayImage() 方法将图片显示到界面上
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri,null);
        displayImage(imagePath);
    }

    private void displayImage(String imagePath) {
        if (imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            bitmap = Bitmap.createScaledBitmap(bitmap,200,200,true);

            bitmap = toRoundBitmap(bitmap);//调用自己写的方法把bitmap转成圆形
            index = "1";
            info = imagePath;
            updatepicture();//把图片路径存入数据库
            img_user.setImageBitmap(bitmap);
        }else{
            Toast.makeText(this,"failed to gei image",Toast.LENGTH_SHORT).show();
        }
    }
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //  通过 Uri 和 selection 来获取真实图片的路径
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor != null){
            if (cursor.moveToNext()){
                //  MediaStore.Images.Media.insertImage —— 得到保存图片的原始路径
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    private void openAlbum() {
        /**
         *      启动相册程序
         */
        //  action —— android.intent.action.GET_CONTENT
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        //  该函数表示要查找文件的mime类型（如*/*），这个和组件在manifest里定义的相对应，但在源代码里
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO);    //打开相册,用自定义常量 —— CHOOSE_PHOTO来作为case处理图片的标识
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }else {
                    Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
    /**
     * 把bitmap转成圆形
     * */
    public Bitmap toRoundBitmap(Bitmap bitmap){
        int width=bitmap.getWidth();
        int height=bitmap.getHeight();
        int r=0;
        //取最短边做边长
        if(width<height){
            r=width;
        }else{
            r=height;
        }
        //构建一个bitmap
        Bitmap backgroundBm=Bitmap.createBitmap(width,height, Bitmap.Config.ARGB_8888);
        //new一个Canvas，在backgroundBmp上画图
        Canvas canvas=new Canvas(backgroundBm);
        Paint p=new Paint();
        //设置边缘光滑，去掉锯齿
        p.setAntiAlias(true);
        RectF rect=new RectF(0, 0, r, r);
        //通过制定的rect画一个圆角矩形，当圆角X轴方向的半径等于Y轴方向的半径时，
        //且都等于r/2时，画出来的圆角矩形就是圆形
        canvas.drawRoundRect(rect, r/2, r/2, p);
        //设置当两个图形相交时的模式，SRC_IN为取SRC图形相交的部分，多余的将被去掉
        p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        //canvas将bitmap画在backgroundBmp上
        canvas.drawBitmap(bitmap, null, rect, p);
        return backgroundBm;
    }

    //动态申请读取手机内存的权限：
    private void requestWritePermission(){
        //  动态申请WRITE_EXTERNAL_STORAGE 这个危险权限。因为相册中的照片时存储在SD卡上的，我们从SD卡中读取照片就需要申请这个权限
        //  WRITE_EXTERNAL_STORAGE  ——  同时授权程序对SD卡读和写的能力
        if (ActivityCompat.checkSelfPermission(EditUserInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(EditUserInfoActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
    }

    //存照片进数据库：
    private void updatepicture() {
        values = new ContentValues();
        values.put("picture",info);
        values.put("flag",index);
        userdao.updateUserInfo(values,User.USERNAME);
        //重新更新user的头像存储路径和flag
        User.USERPICTURE = userdao.getUserPictureByUsername(User.USERNAME);
        User.FLAG = userdao.getUserPictureFlagByUsername(User.USERNAME);

    }
    //弹出popueWindow让用户选择上传头像的方式：
    private void showPopueWindow(){
        View popView = View.inflate(this,R.layout.upload_icon_popuewindow,null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
        //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels*1/3;

        final PopupWindow popupWindow = new PopupWindow(popView,weight,height);
       // popupWindow.setAnimationStyle(R.style.anim_popup_dir);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {//本地相册
            @Override
            public void onClick(View v) {//相册
                requestWritePermission();
                openAlbum();        //  用户授权了权限申请之后就会调用该方法
                popupWindow.dismiss();

            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {//相机拍摄
            @Override
            public void onClick(View v) {//相机
                //获取本地时间作为图片的名字，防止拍了多张照片时，出现图片覆盖导致之前图片消失的问题
                SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());
                String str = format.format(curDate);

                /**
                 *          创建File对象，用于存储拍照后的照片
                 *          第一个参数：  是这张照片存放在手机SD卡的对应关联缓存应用
                 *          第二个参数：  这张图片的命名
                 */
                File outputImage = new File(getExternalCacheDir(),str+".jpg");
                try {
                    if (outputImage.exists()){          //  检查与File对象相连接的文件和目录是否存在于磁盘中
                        outputImage.delete();           //  删除与File对象相连接的文件和目录
                    }
                    outputImage.createNewFile();        //  如果与File对象相连接的文件不存在，则创建一个空文件
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (Build.VERSION.SDK_INT >= 24){       //  如果运行设备的系统版本高于 Android7.0
                    /**
                     *          将File对象转换成一个封装过的Uri对象
                     *          第一个参数：  要求传入Context参数
                     *          第二个参数：  可以是任意唯一的字符串
                     *          第三个参数：  我们刚刚创建的File对象
                     */
                    imageUri = FileProvider.getUriForFile(EditUserInfoActivity.this,"ccv.turbosnail.cameraalbumtest.fileprovider2",outputImage);
                }else{                  //  如果运行设备的系统版本低于 Android7.0
                    //  将File对象转换成Uri对象，这个Uri对象表示着output_image.jpg 这张图片的本地真实路径
                    imageUri = Uri.fromFile(outputImage);
                }
                /**
                 *      启动相机程序
                 */
                //  将Intent的action指定为 拍照到指定目录 —— android.media.action.IMAGE_CAPTURE
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                //  指定图片的输出地址
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                //  在通过startActivityForResult()，来启动活动，因此拍完照后会有结果返回到 onActivityResult()方法中
                startActivityForResult(intent,TAKE_PHOTO);  //  打开相机，用自定义常量 —— TAKE_PHOTO来作为case处理图片的标识

                popupWindow.dismiss();

            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM,0,50);

    }
}

